﻿using MyDLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winform_用户界面客户端
{
    public partial class Map_Editor : Form
    {
        public Map_Editor()
        {
            InitializeComponent();
        }

        
        private void Map_Editor_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {                
                string drop_Path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                Array array = (System.Array)e.Data.GetData(DataFormats.FileDrop);
                MyOutPut("发现鼠标有拖动对象:");
                foreach (string s in array)                    
                    MyOutPut(s);
                MyOutPut("输出完毕");                
                e.Effect = DragDropEffects.Link;
            }
        }

        private List<string> temp_TargetInfo = new List<string>();        
        private List<string> Targets_Path = new List<string>();
        private void Map_Editor_DragDrop(object sender, DragEventArgs e)
        {            
            Array array = (System.Array)e.Data.GetData(DataFormats.FileDrop);            
            foreach (string drop_Path in array)
            {
                if (File.Exists(drop_Path) || Directory.Exists(drop_Path))
                {
                    if (Targets_Path.Contains(drop_Path))
                        return;
                    else
                        Targets_Path.Add(drop_Path);

                    //向LV_Target_Input列表中添加新的一项
                    temp_TargetInfo.Clear();
                    //添加目标名
                    temp_TargetInfo.Add(drop_Path.Substring(drop_Path.LastIndexOf('\\') + 1));
                    //添加路径
                    temp_TargetInfo.Add(drop_Path.Substring(0, drop_Path.LastIndexOf('\\') + 1));

                    //temp_TargetInfos.Add(new List<string>(temp_TargetInfo));
                    LV_Add_Target(temp_TargetInfo);
                }
                else
                {
                    MyOutPut("无法处理的拖动型对象");
                    continue;
                }
            }
        }

        private void Map_Editor_DragLeave(object sender, EventArgs e)
        {
            //Root_Path.Text = old_path;
        }

        public void MyOutPut(string text)
        {
            if (text == "")
                return;
            RTB_Log.Text += RTB_Log.Text == "" ? text : "\n" + text;
            RTB_Log.SelectionStart = RTB_Log.Text.Length;
            RTB_Log.ScrollToCaret();
        }

        /// <summary>
        /// 向LV_Target_Input列表中添加一个新项
        /// </summary>
        /// <param name="Target_Info"></param>
        public void LV_Add_Target(List<string> Target_Info)
        {            
            ListViewItem l = new ListViewItem();
            l.Text = (LV_Target_Input.Items.Count + 1).ToString();
            l.SubItems.Add(Target_Info[0]);
            l.SubItems.Add(Target_Info[1]);
            LV_Target_Input.Items.Add(l);
        }

        

        private void RemoveLastTarget(object sender, EventArgs e)
        {
            if (LV_Target_Input.Items.Count != 0)
            {
                ListViewItem l=LV_Target_Input.Items[LV_Target_Input.Items.Count - 1];
                Targets_Path.Remove(l.SubItems[2].Text + l.SubItems[1].Text);
                l.Remove();                
            }
        }

        /// <summary>
        /// 目前被选择的“目标”的数据库
        /// </summary>
        private MySqlite selected_DB=null;   

        private void LV_Target_Input_MouseClick(object sender, MouseEventArgs e)
        {
            //获取选择的目标项
            ListViewItem l = LV_Target_Input.SelectedItems[0];

            string target_Path = l.SubItems[2].Text;
            string target_Name = l.SubItems[1].Text;
            //确认是否有数据库文件存在，数据库对象是否已经打开
            MySqlite m = null;
            if (RB_cur_dir.Checked) 
                m=GlobalValue.OpenDB(target_Path);
            else if(RB_src_dir.Checked)
            {
                int result = 0;
                foreach(MySqlite temp_m in GlobalValue.DB_List.Values)
                {                    
                    result = temp_m.Target_is_Exist(target_Name);
                    if (result == 1)
                    {
                        m = temp_m;
                        break;
                    }
                }
                if(result==0)//如果所有数据库中均没有该文件
                {
                    MyOutPut("没有搜索到此文件的源文件。");
                    return;
                }
            }
            else
            {
                MyOutPut("搜索模式错误");
                return;
            }

            /*
            MySqlite m = GlobalValue.GetDB(target_Path);            
            if (m == null)//如果数据库还没有打开
            {
                //检测数据库文件是否存在
                if (!File.Exists(target_Path + GlobalValue.DB_Name))//如果不存在
                {
                    //创建并打开数据库  ！：可优化
                    m = new MySqlite();
                    m.Create_Open_DB(target_Path + GlobalValue.DB_Name);
                    GlobalValue.AddDB(target_Path, m);
                    MyOutPut("没有发现数据库对象，现已创建并打开");
                }
                else//如果存在
                {
                    //创建并打开数据库
                    m = new MySqlite();
                    m.Create_Open_DB(target_Path + GlobalValue.DB_Name);
                    GlobalValue.AddDB(target_Path, m);
                    MyOutPut("发现对应的数据库文件，现已打开");
                    
                }
            }*/

            selected_DB = m;
            MyOutPut("标签信息来源:" + selected_DB.DB_Path);

            //搜索其标签。如果没有则进行提示。
            List<string> TagNames_List = m.Get_Tags_By_TargetName(target_Name);
            //搜索其备注
            string comment = m.Get_Target_Comment(target_Name);
            MyOutPut("备注为：" + comment);
            RTB_TargetComment.Text = comment;

            LV_TagsList.Items.Clear();
            if (TagNames_List == null)
            {
                MyOutPut("没有相关标签");
                return;
            }            
            LV_TagsList.BeginUpdate();
            foreach (string tag in TagNames_List)
            {
                MyOutPut(tag);
                ListViewItem lvi = new ListViewItem((LV_TagsList.Items.Count + 1).ToString());
                lvi.SubItems.Add(tag);
                LV_TagsList.Items.Add(lvi);
            }
            LV_TagsList.EndUpdate();

            DGV_TagsList.Rows.Clear();            
            foreach (string tag in TagNames_List)
            {
                DataGridViewRow r = new DataGridViewRow();
                DGV_TagsList.Rows.Add(DGV_TagsList.Rows.Count.ToString(), tag);
            }
        }

        private void DGV_TagsList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string s = e.ToString();

            string target_name = LV_Target_Input.SelectedItems[0].SubItems[1].Text;
            string new_tag_name = DGV_TagsList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            if (e.ColumnIndex==1)//如果修改标签名
            {
                if (old_tag_name != "")
                {
                    //删除关系
                    selected_DB.Delete_Map_Target_Tag(target_name, old_tag_name);
                    MyOutPut("删除关系:" + target_name + " " + old_tag_name);
                }
                //重新添加关系
                selected_DB.Add_Map_Target_Tag(target_name, new_tag_name);
                MyOutPut("添加关系:" + target_name+" "+new_tag_name);
                selected_DB.Add_Map_Tag_Tag(new_tag_name, "来自v.0.0.0.1版本");
            }

        }

        private string old_tag_name = "";
        private void DGV_TagsList_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex == 1 && DGV_TagsList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value!=null)//如果是标签格
            {
                old_tag_name = DGV_TagsList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }
        }

        private void Map_Editor_FormClosing(object sender, FormClosingEventArgs e)
        {
            base.Hide();
            
        }

        private void Map_Editor_DragEnter_1(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {                
                Watcher_Path.Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                e.Effect = DragDropEffects.Link;
            }
        }

        private void CB_watcher_switch_CheckedChanged(object sender, EventArgs e)
        {
            MyOutPut(Watcher_Path.Text);            
            switch(CB_watcher_switch.CheckState)
            {
                case CheckState.Checked:
                    fileSystemWatcher1.Path = Watcher_Path.Text;
                    fileSystemWatcher1.EnableRaisingEvents = true;
                    MyOutPut("开始监听:" + Watcher_Path.Text);
                    break;
                case CheckState.Unchecked:
                    fileSystemWatcher1.EnableRaisingEvents = false;
                    MyOutPut("关闭监听");
                    break;
            }

        }

        private List<string> ready_to_deleted = new List<string>();

        private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
        {
            //忽略数据库文件及其创建的临时文件
            if (e.Name == GlobalValue.DB_Name || e.Name == GlobalValue.DB_TempName)
                return;
            string db_path = e.FullPath.Substring(0, e.FullPath.LastIndexOf('\\') + 1);
            //获取对应数据库对象
            MySqlite m =GlobalValue.OpenDB(db_path);
            //从数据库中删除相关信息
            m.Delete_Target_by_Name(e.Name);
            MyOutPut("删除目标:" + e.Name);
        }

        private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
        {
            //忽略数据库文件及其创建的临时文件
            if (e.Name == GlobalValue.DB_Name || e.Name == GlobalValue.DB_TempName)
                return;

            MyOutPut("添加目标:" + e.Name);
            if (Targets_Path.Contains(e.FullPath))
                return;
            else
                Targets_Path.Add(e.FullPath);

            //向LV_Target_Input列表中添加新的一项
            temp_TargetInfo.Clear();
            //添加目标名
            temp_TargetInfo.Add(e.FullPath.Substring(e.FullPath.LastIndexOf('\\') + 1));
            //添加路径
            temp_TargetInfo.Add(e.FullPath.Substring(0, e.FullPath.LastIndexOf('\\') + 1));
            LV_Add_Target(temp_TargetInfo);
        }

        private void Map_Editor_FormClosed(object sender, FormClosedEventArgs e)
        {
            fileSystemWatcher1.EnableRaisingEvents = false;
        }

        private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
        {
            MyOutPut("修改文件名: 原:" + e.OldName + " 现在名为:" + e.Name);
            string db_path = e.FullPath.Substring(0, e.FullPath.LastIndexOf('\\') + 1);
            //获取对应数据库对象
            MySqlite m = GlobalValue.OpenDB(db_path);
            m.Update_Target_Name(e.OldName, e.Name);
            
        }

        /// <summary>
        /// 更新目标的备注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string target_Name = LV_Target_Input.SelectedItems[0].SubItems[1].Text;
            selected_DB.Update_Target_Comment(target_Name, RTB_TargetComment.Text);
            MyOutPut(target_Name + "备注被更改为：" + RTB_TargetComment.Text);
        }
    }
    

}
